﻿// 项目：	Guan.CMS.Web - Guan.CMS
// 文件名：	ProductCategoryController.cs
// 
// 修改时间：2013-03-09 22:01
// 修改人：	Cooclsee

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using Guan.CMS.CommandProcessor.Dispatcher;
using Guan.CMS.Data.Repositories;
using Guan.CMS.Domain.Commands.ProductCategory;
using Guan.CMS.Domain.Services;
using Guan.CMS.Model.Entities;
using Guan.CMS.Web.Core.ActionFilters;
using Guan.CMS.Web.Core.Extensions;
using Guan.CMS.Web.Core.Models;
using Guan.CMS.Web.Helpers;
using Guan.CMS.Web.ViewModels.ProductCategory;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;

namespace Guan.CMS.Web.Areas.Admin.Controllers
{
    [CmsAuthorize(Roles.Admin)]
    public class ProductCategoryController : Controller
    {
        private readonly IProductCategoryRepository _productCategoryRepository;
        private readonly IProductCategoryService _productCategoryService;
        private readonly ICommandBus _commandBus;

        public ProductCategoryController(IProductCategoryRepository productCategoryRepository,IProductCategoryService productCategoryService, ICommandBus commandBus)
        {
            _productCategoryRepository = productCategoryRepository;
            _productCategoryService = productCategoryService;
            this._commandBus = commandBus;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List()
        {
            //var list = this.GetListById(0);
            //return this.View(list);
            var list = _productCategoryRepository.GetList(true).AsEnumerable();
            var vm = list.ToProductCategoryTree(isExpanded: true);
            return this.View(vm);
        }

        public ActionResult ListAjax([DataSourceRequest] DataSourceRequest request)
        {
            return Json(GetListById(0).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        public ActionResult HierarchyBinding_List(int? id, [DataSourceRequest] DataSourceRequest request)
        {
            var list = GetListById(id);
            return Json(list.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        public ActionResult Tree()
        {
            return View();
        }

        /// <summary>
        /// 通过ID获取树
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult TreeData(int? id)
        {
            var list = _productCategoryRepository.GetList();
            IList<ProductCategory> list2;
            if (id.HasValue && id != 0)
            {
                list2 = list.Where(c => c.ParentId == id.Value).ToList();
            }
            else
            {
                list2 = list.Where(c => !c.ParentId.HasValue || c.ParentId == 0).ToList();
            }
            var result = list2.Select(c => new {id = c.Id, c.Name, hasChildren = list.Any(a => a.ParentId == c.Id)});
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        private IEnumerable<ProductCategoryTree> GetListById(int? id)
        {
            var list = _productCategoryService.GetChildrenNodesById(id);
            var vm = Mapper.Map<IEnumerable<ProductCategory>, IEnumerable<ProductCategoryTree>>(list.AsEnumerable());
            return vm;
        }

        public ActionResult Edit(int? id)
        {
            ProductCategoryFormModel form = null;
            if (id.HasValue && id.Value != 0)
            {
                var category = _productCategoryRepository.GetById(id.Value);
                form = Mapper.Map<ProductCategory, ProductCategoryFormModel>(category);
            }
            else
            {
                form = new ProductCategoryFormModel();
            }
            var categoryList = _productCategoryService.GetChildrenNodesById(0);
            var selectList = new List<SelectListItem> {new SelectListItem {Value = "", Text = " ",Selected = form.ParentId==null}};
            selectList.AddRange(categoryList.Select(c=> new SelectListItem{Text = c.Name,Value = c.Id.ToString(),Selected = form.ParentId==c.Id}));
            ViewBag.ParentId = selectList;
            return this.View(form);
        }

        [HttpPost]
        public ActionResult Edit(ProductCategoryFormModel form)
        {
            if (ModelState.IsValid)
            {
                var command = Mapper.Map<ProductCategoryFormModel, AddOrUpdateProductCategoryCommand>(form);
                var errors = _commandBus.Validate(command);
                ModelState.AddModelErrors(errors);
                if (ModelState.IsValid)
                {
                    var result = _commandBus.Submit(command);
                    if (result.Success)
                    {
                        return RedirectToAction("List");
                    }
                }
            }
            var categoryList = _productCategoryService.GetChildrenNodesById(0);
            var selectList = new List<SelectListItem> { new SelectListItem { Value = null, Text = "", Selected = form.ParentId == null } };
            selectList.AddRange(categoryList.Select(c => new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = form.ParentId == c.Id }));
            ViewBag.ParentId = selectList;
            return this.View(form);
        }

        public ActionResult Delete(int id)
        {
            var command = new RemoveProductCategoryCommand(id);
            var result = _commandBus.Submit(command);
            if (result.Success)
            {
                return RedirectToAction("List");
            }
            return RedirectToAction("Edit", new {id});
        }

        public ActionResult SelectCategory(int[] categoryList)
        {
            /*ViewBag.CategoryList = categoryList;
            var tree = _productCategoryService.GetTree();
            return View(tree);*/
            return this.View();
        }
    }
}